<template>
  <a-drawer
    v-model:visible="vdata.visible"
    :title="vdata.isAdd ? '新增模板' : '修改模板信息'"
    width="90%"
    :maskClosable="false"
    @close="onClose"
  >
    <a-row>
      <a-col :span="14">
        <div style="border-right: 1px solid; padding-right: 10px;">
          <a-form
            ref="infoFormRef"
            :rules="vdata.rules"
            :model="vdata.record"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-form-item label="模板别名" name="shellAlias">
              <a-input v-model:value="vdata.record.shellAlias" style="width:220px" />
            </a-form-item>

            <a-form-item label="选择渲染模板" name="styleCode">
              <a-radio-group v-model:value="vdata.record.styleCode" :disabled="!vdata.isAdd" @change="changeShellFunc">
                <a-radio value="shellA">模板A</a-radio>
                <a-radio value="shellB">模板B</a-radio>
                <a-radio value="shellC">模板C</a-radio>
              </a-radio-group>
            </a-form-item>

            <component :is="vdata.currentComponent" ref="shellComponentRef" />
          </a-form>
        </div>
      </a-col>
      <a-col :span="10">
        <div style="display: flex; justify-content: center;">
          <div>
            <img v-if="vdata.viewImgSrc" :src="vdata.viewImgSrc" style="max-width: 400px; border: 1px solid darkgrey">
          </div>
        </div>
      </a-col>
    </a-row>

    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="onClose"><close-outlined />取消</a-button>
      <a-button type="primary" @click="onSubmit"><check-outlined />保存</a-button>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { API_URL_QRC_SHELL_LIST, $qrcShellView, req } from '@/api/manage'
import {ref, reactive, getCurrentInstance, inject, provide, nextTick } from 'vue'
import ruleGenerator from '@/utils/ruleGenerator'

const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

const infoFormRef = ref()

const shellComponentRef = ref()

// 注入列表页刷新事件
const listPageSearchFunc : any = inject('listPageSearchFunc')

const vdata : any = reactive ({

  rules: {
    shellAlias: [ruleGenerator.requiredInput('别名')],
    styleCode: [ruleGenerator.requiredSelect('渲染模板')]
  },

  isAdd: true, // 新增 or 修改
  visible: false, // 抽屉开关

  recordId: null, //模板信息
  record: {}, // 当前模板信息
  viewImgSrc: '', //预览图

  currentComponent: null, // 动态组件

})

// 注入预览函数
provide('viewFunc', viewFunc)

// 抽屉显示
function show (recordId) {

  // 初始化
  vdata.recordId = recordId
  vdata.record = {}
  vdata.viewImgSrc = '' // 不再显示预览图

  componentRender(null, null) //置空

  vdata.isAdd = !recordId

  // 新增： 默认选中模板A
  if(vdata.isAdd){
    vdata.record.styleCode = 'shellA'
    componentRender(vdata.record.styleCode, () => {
    shellComponentRef.value.pageRender(null) //渲染
  })
  }

  if(recordId){
    req.getById(API_URL_QRC_SHELL_LIST, recordId).then((res) => {
      vdata.record = res
      let dbConfigInfo = JSON.parse(res.configInfo)

      componentRender(res.styleCode, () => {
        shellComponentRef.value.pageRender(dbConfigInfo) //渲染
      }) // 渲染模板
    })
  }

  vdata.visible = true
}
function onClose () {
  vdata.visible = false
}

// 点击新增 
function onSubmit(){

  infoFormRef.value.validate().then(() => {
      vdata.record.configInfo = shellComponentRef.value.genReqConfigModel()

      if(vdata.isAdd){

            req.add(API_URL_QRC_SHELL_LIST, vdata.record).then((res) => {
            $infoBox.message.success('添加成功')
            listPageSearchFunc()
            vdata.visible = false
          })
      }else{

            req.updateById(API_URL_QRC_SHELL_LIST, vdata.recordId, vdata.record).then((res) => {
            $infoBox.message.success('更新成功')
            listPageSearchFunc()
            vdata.visible = false
          })
      }
  })

}

// 预览图片 
function viewFunc(){

  $qrcShellView(vdata.record.styleCode, shellComponentRef.value.genReqConfigModel()).then(res => {
    vdata.viewImgSrc = res
  })
}

// 组件渲染
function componentRender(styleCode, callback){

  if(!styleCode){
    vdata.currentComponent = null
    return false
  }

// 页面前缀 首字母大写 （根据ifCode进行匹配）
  let currentComponentNamePrefix = styleCode.substring(0, 1).toUpperCase() + styleCode.substring(1)
  // 动态引入组件 
  import(`./config/${currentComponentNamePrefix}Config.vue`).then((module) => {
    vdata.currentComponent = module.default
      nextTick(() => {
        callback && callback() // 回调函数  
      })
      
  })

}

// 切换模板
function changeShellFunc(){
  componentRender(vdata.record.styleCode, () => {
    shellComponentRef.value.pageRender(null) //渲染
  })
}


defineExpose({show})

</script>

<style lang="less" scoped>
.uploadDiv{
  width: 80%; margin-bottom: 10px;
}
</style>
